<template>
  <div class="model-page">
    <div class="page-full-teacherDetail pBtm">
      <!-- 顶部 -->
      <topHeader :show-left='true' :show-right='true' title="大师详情"></topHeader>

      <!-- 主体版块1 大师基本信息 -->
      <section class="basic_wrapper">
        <dl>
          <dt>
            <img v-if="data_master.figure_img" :src="imgUrl(data_master.figure_img)" alt />
          </dt>
          <dd class="_name">
            {{data_master.name}}
            <i></i>
          </dd>
          <dd class="_des fontHideOne">{{data_master.image_desc}}</dd>
        </dl>
        <div class="other">
          <div class="_item">
            <span class="s0">解答数</span>
            <span class="s1">{{data_master.answernum}}</span>
          </div>|
          <div class="_item">
            <span class="s0">从业时间</span>
            <span class="s1">{{data_master.employment_time}}年</span>
          </div>|
          <div class="_item">
            <span class="s0">评价数</span>
            <span class="s1">{{data_master.pl_num}}</span>
          </div>
        </div>
      </section>

      <!-- 主体版块2 -->
      <section class="intro_wrapper">
        <!-- 音频s -->
        <div class="c_audio" v-if="data_master.voice">
          <span>{{countdown}}''</span>
          <div class="progress">
            <p class="realProgress" :style="{'width':realProgressW+'rem'}"></p>
          </div>
          <i :class="isPlay?'i_play':'i_pause'" @click="play()"></i>
        </div>
        <!-- 音频e -->

        <div class="c_cmt" v-if="user_cmt&&user_cmt.length!=0">
          <div class="mTt">用户评价</div>
          <ul>
            <li v-for="(i,idx) in user_cmt" :key="'keyCmt_'+idx">{{i}}</li>
          </ul>
        </div>

        <div class="c_skill" v-if="skills&&skills.length!=0">
          <div class="mTt">擅长领域</div>
          <ul>
            <li v-for="(i,idx) in skills" :key="'keyCmt_'+idx">{{i}}</li>
          </ul>
        </div>

        <div id="servicePro" class="c_service" v-if="data_service&&data_service.length!=0" ref="servicePro">
          <div class="mTt">服务项目</div>
          <ul :class="{'active':serviceLen!=4}">
            <li v-show="idx<serviceLen" v-for="(i,idx) in data_service" :key="'radio_'+idx" @click="changeServie(idx)">
              <div class="img">
                <img :src="imgUrl(i.icon)" alt="">
              </div>
              <p><span class="name">{{i.type_name}}</span><span v-if="i.price">￥{{i.price}}</span></p>
              <span class="radio" :class="{'active':curServiceIdx==idx}"></span>
            </li>
            <div class="more" @click="toViewMore()">{{tipMore}}<i class="i_down" :class="{'active':isViewMore==true}"></i></div>
          </ul>

        </div>

      </section>

      <!-- 主体版块3 个人介绍-->
      <section class="perIntro_wrapper">
        <div class="mTitle2">
          <img src="../../../static/image/teacherDetail/title_intro.png" alt="">
        </div>
        <div class="c_img">
          <img v-if="data_master.introduce_img" :src="imgUrl(data_master.introduce_img)" alt="">
        </div>
        <div class="c_des" v-html="data_master.mastermsg"></div>
        <div class="c_experience" v-if="data_master.training">
          <div class="mTitle">培训学习经历</div>
          <ul class="tree_list">
            <li v-for="(i,idx) in data_master.training" :key="'experience_'+idx">
              <p class="p0"><i></i>{{i.start_time}} - {{i.end_time}}</p>
              <p class="p1">{{i.content}}</p>
            </li>
          </ul>
        </div>
        <div class="c_honors" v-if="data_master.association">
          <div class="mTitle">协会资质</div>
          <p v-html="data_master.association"></p>
        </div>
        <p class="c_foot"><i></i>以上信息已通过吉命严格审查，真实有效</p>
      </section>

      <!-- 主体版块4 服务案例 -->
      <section class="service_case_wrapper">
        <div class="mTitle2">
          <img src="../../../static/image/teacherDetail/title_case.png" alt="">
        </div>
        <div class="c_train">
          <div class="mTitle">服务案例数</div>
          <p>截止到目前，服务过的用户超过<span>{{data_master.answernum}}</span>名，0退款！</p>
        </div>
        <div class="c_project" v-if="data_master.partnership&&data_master.partnership.length!=0">
          <div class="mTitle">合作过的企业项目</div>
          <ul>
            <li>
              <dl v-for="(i,idx) in data_master.partnership" :key="'company_'+idx">
                <dt>
                  <img :src="imgUrl(i.imgurl)" alt="">
                </dt>
                <dd>{{i.name}}</dd>
              </dl>
            </li>
          </ul>
        </div>
        <div class="c_case" v-if="data_master.cases">
          <div class="mTitle">神准真实案例</div>
          <div class="content" v-html="data_master.cases"></div>
        </div>
      </section>

      <!-- 主体版块5 评论反馈 -->
      <section class="cmt_feedback_wrapper" v-if="data_cmtCount">
        <div class="mTitle3">评论反馈（{{data_cmtCount}}）</div>
        <ul class="mComment_list">
          <li v-for="(i,idx) in data_cmtList" :key="'cmt_'+idx">
            <div class="c_user">
              <div class="left">
                <span class="name">{{i.user_name}}</span>
                <div class="stars">
                  <i v-for="(si,sidx) in starClass(i.score,'i_star_on','i_star_half','i_star_gray')" :class="si" :key="'level'+sidx"></i>
                </div>
                <span class="num">{{i.score}}分</span>
              </div>
              <span class="right">已购买：{{i.project_name}}</span>
            </div>
            <p class="c_des">{{i.content}}</p>
          </li>
        </ul>
        <div class="c_btn" @click="toViewCmt(data_master.mid)">查看全部{{data_cmtCount}}条评论<i></i></div>
      </section>
      
      <!-- 主体版块6 咨询流程 -->
      <section class="consult_process_wrapper">
        <div class="mTitle3">咨询流程</div>
        <div class="c_progress">
          <img src="../../../static/image/teacherDetail/consult_progress.png" alt="">
        </div>
        <div class="c_info">
          <p>质量保证：</p>
          <p>1、若遇到不满意，可选择退款</p>
          <p>2、若对老师的解答有疑惑，可免费咨询2次</p>
        </div>
      </section>

      <!-- 底部 -->
      <footer class="footer_wrapper">
        <div class="c_customer" @click="popKefu()">
          <i></i>客服
        </div>
        <div class="c_btn mBtn_hole" @click="toSubOrder()">立即问老师<span v-if="data_master.ordering_num">（今日已排队{{data_master.ordering_num}}人）</span></div>
      </footer>
    </div>

    <kefu :showStatus="showStatus" @changeStatus='showStatus=$event'></kefu>
  </div>
</template>

<script>
import topHeader from '@/components/topHeader';
import loading from '@/components/pageLoading';
import tool from '@/assets/js/tool.js';
import kefu from '@/components/kefuPopup';
import { clearInterval, setInterval, setTimeout} from 'timers';
export default {
  components:{
    topHeader,
    kefu
  },
  data () {
    return {
      tipMore:'查看更多',
      audio:new Audio(),//音频
      audioSrc:'',
      countdown:'',//倒计时
      isPlay:false,//false：按钮为暂停状态  true：按钮为播放状态
      realProgressW:'',//进度条真实长度
      init_timer:null,//音频初始化定时器
      timer:null,//音频播放or定时器
      curServiceIdx:-1,//服务项目单选
      curTypeId:'',
      serviceLen:4,
      isViewMore:false,//查看更多 ，默认false
      showStatus:false,
      user_cmt:'',//用户评论
      skills:'',//擅长领域
      fetch_data:{},//page数据
      data_master:{},//大师相关
      data_service:{},//服务项目
      data_partner:{},
      data_cmtCount:'',//评论反馈列表个数
      data_cmtList:[],//评论反馈列表
      ordercode:'',//订单号
    };
  },
  created () {
    this.$store.commit('changePageLoading',true);
    this.fetch_page();
    window.scroll(0,0)
  },
  deactivated() {//keep-alive销毁时，暂停播放
    this.pause(this.audio);
  },
  methods: {
    imgUrl(url){
      if(url){
        return tool.imgUrl(url,true);
      }else{
        return require('../../../static/image/teacherDetail/cmpy.png');
      }
    },
    starClass(level,on,half,gray){
      return tool.starClass(level,on,half,gray);
    },
    initProgress(){
      let o = this.audio;
      if(this.audioSrc){
        o.src = this.audioSrc;
      }
      var init_timer=setInterval(() => {
        var $duration = Math.floor(o.duration);//音频总长度（秒）
        if($duration){
          var m = Math.floor($duration / 60);//分
          var s = Math.floor($duration % 60);//秒
          m = m<10?'0'+m:m;
          s = s<10?'0'+s:s;
          this.countdown = `${m}:${s}`;
          clearInterval(init_timer);
        }
      }, 300);

      
    },
    play(){
      let o = this.audio;
      if(this.audioSrc){
        o.src =this.audioSrc;
      }
      //默认为暂停状态，点击时播放
      if(!this.isPlay){
        o.play();
        this.isPlay = true;//播放状态
        var $progressW = 398/75;//进度条总宽度
        var $duration = "";//音频总长度（秒）
        var $currentTime = "";//当前音频播放长度（秒）
        var $countdown = "";//倒计时（秒）
        var $realProgressW = "";//进度条宽度（px）
        this.timer = setInterval(()=>{
          $duration = Math.floor(o.duration);
          $currentTime = Math.floor(o.currentTime);
          console.log('总时间',$duration,'当前进度',$currentTime);
          if($currentTime > $duration){
            this.isPlay = false;
            this.countdown = "00:00";
            return;
          }
          if($currentTime == $duration){
             clearInterval(this.timer);
          }
          //倒计时为总音频长度-当前音频播放长度
          $countdown = $duration - $currentTime;
          var m = Math.floor($countdown/60);//分
          var s = Math.floor($countdown%60);//秒
          m = m<10?'0'+m:m;
          s = s<10?'0'+s:s;
          // 进度条进度=（定义的进度条总长度*音频当前播放时间）/音频总时间
          $realProgressW = ( $progressW * $currentTime)/$duration;
          this.countdown = `${m}:${s}`;
          this.realProgressW = $realProgressW;
        },50); 
      }else{
       this.pause(o);
      }
    },
    pause(o){
      clearInterval(this.timer);
      o.pause();//暂停
      this.isPlay = false;
    },
    popKefu(){
      this.showStatus = !this.showStatus;
    },
    /**
      @func 
      @desc:初始化服务项目默认值
            - 若上一页从选择了咨询类型A，则curServiceIdx默认为A的索引
            - 若上一页从大师列表直接进入,则curServiceIdx为-1
            优化：state.curTypeId 表示咨询项目类型id
    */ 
    initServiceIdx(){
      if(this.$route.query.type_id){
        var arr=this.data_service;
        arr.map((value , index )=>{ //value为遍历的当前元素，index为当前索引，array为正在操作的数组
          if(value.id == this.$route.query.type_id){
            return this.curServiceIdx = index;
          }
        }) 
      } else{
        this.curServiceIdx = -1;
      }
    },
    /**
      @func 
      @desc:点击服务项目，切换选项
           - 点击时，选中索引curServiceIdx为当前索引
    */
    changeServie(idx){
      this.curServiceIdx = idx;
    },
    /**
      @func 
      @desc:切换服务项目查看更多，数据加载条数变化 
            - isViewMore： 若为true：执行查看更多操作，若为false:只显示4条
    */
    toggeleServiece(){
      this.data_service=this.fetch_data.qestion_type;
       // 服务项目长度
      if(!this.isViewMore){
        this.serviceLen=4;
        this.tipMore = '查看更多';
      }else{
        this.serviceLen=this.data_service.length;
        this.tipMore = '收起';
      }
    },
    /**
      @func 
      @desc:点击服务项目查看更多，isViewMore状态变化，数据变化，需再次调用toggeleServiece();
            - isViewMore： 若为true：执行查看更多操作，若为false:只显示4条
    */
    toViewMore(){
      this.isViewMore = !this.isViewMore;
      this.toggeleServiece();
    },
    /**
      @func 
      @desc:查看所有评论
      @param:mid - 参数大师id
    */
    toViewCmt(mid){
      this.$router.push({
        path:`/allComment?mid=${mid}`,
      });
    },
    changeStatus(){
      this.showStatus = false;
    },
    fetch_page(){
      var type_id = this.$route.query.type_id;
      var mid = this.$route.query.mid;
      if(type_id){
        var param={
          type_id:type_id
        }
      }
      if(mid){
        var param={
          mid:mid
        }
      }
      this.$fetch.post('/app/Jmyc/auto_mate_master',param).then((res)=>{
        if(res.code==200){
          console.log(tool.timestampToTime(res.time))
          this.fetch_data = res.data;
          // 大师
          this.data_master = this.fetch_data.master_info; 
          // 服务项目
          this.toggeleServiece();
          this.initServiceIdx();
          // 音频
          this.audioSrc=this.data_master.voice;
          this.initProgress();
          // 用户评论
          this.user_cmt=this.data_master.image_lables.split(" ");
          // 擅长领域
          this.skills = this.data_master.skills.split("、");
          // 合作企业
          this.data_partner = this.data_master.partnership;
          //评论反馈列表个数
          this.data_cmtCount = this.fetch_data.user_pl_list.all_num;
          //评论反馈列表
          this.data_cmtList = this.fetch_data.user_pl_list.data;
          this.$store.commit('changePageLoading',false);
        }
      });
    },
    /**
      @func 
      @desc:点击立即问老师 执行以下操作：判断是否选择服务项目，无滚动至服务项目，有则下单并跳转至确认订单
    */
    toSubOrder(){
      if(this.curServiceIdx==-1){
        this.$vux.toast.text('请选择服务项目!', 'middle');   
         setTimeout(() => {
          let time = setInterval(() => {
            let scroll = document.documentElement.scrollTop || document.body.scrollTop;//兼容安卓app
            if (scroll <= 300) {
              clearInterval(time);
            } else {
              if (scroll >= 350) {
                document.documentElement.scrollTop = scroll -= Math.ceil(scroll / 30);
                document.body.scrollTop = scroll -= Math.ceil(scroll / 30);
              } else {
                clearInterval(time);
              }
            }
          }, 10);
        }, 900);    
        return;
      }
      this.placeOrder();
    },
    // 下单
    placeOrder(){
      //'866472034154769,866472034358089'//测试uid
      var _this =this;
      var params = {
        mid:_this.data_master.mid,//大师id
        type_id:_this.data_service[_this.curServiceIdx].id,//项目类型id
        order_type:'Android',//下单设备（ios，Android）
        uid:_this.$store.state.userID||'869115037298615,869115037349111',//设备唯一id
        cid:_this.data_service[_this.curServiceIdx].cid,//问题id
        activity_id:_this.$route.query.id || '',//活动id
      }
      // console.log('下单参数',params);
      this.$fetch.post('/app/Jmyc/add_order',params).then((res)=>{
        if(res.code == 200){
          _this.ordercode = res.data.ordercode;
          _this.$router.push({
            path:'/confirmOrder',
            query:{
              'ordercode':_this.ordercode,
              'mid': _this.data_master.mid
            }
          })
        }else{
          this.$vux.toast.text(res.msg, 'middle');  
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../assets/css/public.less";
@import "../../assets/css/tml_base.less";
@import "./index.less";
</style>